package com.common.platform.base.config.context;

import org.springframework.data.redis.connection.ReactiveSetCommands;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

public class HttpContext {
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return null;
        } else {
            return requestAttributes.getRequest();
        }
    }
        /**
         * 获取当前请求的Response对象
         */
        public static HttpServletResponse getResponse() {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (requestAttributes == null) {
                return null;
            } else {
                return requestAttributes.getResponse();
        }
    }
    public static Map<String,String> getRequestParameters(){
        HashMap<String,String> values = new HashMap<>();
        HttpServletRequest request =HttpContext.getRequest();
        if (request==null){
            return values;
        }
        Enumeration<String> enumeration = getRequest().getParameterNames();
        while (enumeration.hasMoreElements()){
            String paramName = (String) enumeration.nextElement();
            String paramValue = request.getParameter(paramName);
            values.put(paramName,paramValue);
        }
        return values;
    }
    public static String getIp(){
            HttpServletRequest request =HttpContext.getRequest();
            if (request==null){
                return "127.0.0.1";
            }else{
                return request.getRemoteHost();
            }
    }
}
